#!/usr/bin/env python
## @example example4.py
#  @see example4.c

#####################################################################
# Example for testing segmentation using geodesy and watershed      #
#####################################################################


import os
import sys
import time

from fulguro import *


### PROCEDURES #########################################################
def benchmark(function,nbiter,*args):
    t=time.time()
    for i in range(nbiter):
        function(*args)
    t2=time.time()
    return ((t2-t)*1000)/nbiter



##################################################################
### MAIN #########################################################
##################################################################

imin = flgr2d_load_pgm('../../images/gray/beans.pgm')
imtmp = FLGR_Data2D(imin)
imFilter = FLGR_Data2D(imin)
imDistance = FLGR_Data2D(imin)
imMarker = FLGR_Data2D(imin)
imMaxima = FLGR_Data2D(imin)
imLabel = FLGR_Data2D(imin)
imWatershed = FLGR_Data2D(imin)

nhb1 = FLGR_Data2D(3,3,imin.spp,imin.type,FLGR_RECT,FLGR_8_CONNEX)
nhb2 = FLGR_Data2D(5,5,imin.spp,imin.type,FLGR_RECT,FLGR_8_CONNEX)
nhb3 = FLGR_Data2D(7,7,imin.spp,imin.type,FLGR_RECT,FLGR_8_CONNEX)
nhb4 = FLGR_Data2D(9,9,imin.spp,imin.type,FLGR_RECT,FLGR_8_CONNEX)
nhb5 = FLGR_Data2D(11,11,imin.spp,imin.type,FLGR_RECT,FLGR_8_CONNEX)

flgr2d_replace(imin,imin,"==",255,254,imin)


## Filter
speed = benchmark(flgr2d_open,100,imFilter,imin,nhb1)
print 'Filter time:',speed,'ms'

## Distance
speed = benchmark(flgr2d_replace,1000,imtmp,imFilter,"<=",128,255,0)
print 'Replace SSE2 time:',speed,'ms'
flgr2d_distance(imDistance,imtmp,nhb1.connexity)

## Distance Maxima
flgr2d_regional_hmaxima(imMaxima,imDistance,1,nhb1.connexity)
speed = benchmark(flgr2d_replace,1000,imtmp,imMaxima,">",0,255,0)
print 'Replace time:',speed,'ms'
flgr2d_dilate(imMaxima,imtmp,nhb4)

## Labelize Maxima
flgr2d_label(imLabel, imMaxima, nhb1.connexity)

## Watershed
speed = benchmark(flgr2d_watershed,1,imLabel, imin, nhb1.connexity)
print 'Watershed time:',speed,'ms'


flgr2d_watershed_build_line(imWatershed, imLabel, nhb1.connexity)
flgr2d_replace(imWatershed,imWatershed,"==",1,255,imin)

vmin,vmax = flgr2d_measure_min_max(imLabel)

print 'Coffee Beans number : ',vmax[0]



flgr_display(imFilter,'filter',
             imDistance,'distance',
             imMaxima,'maxima',
             imLabel,'label',
             imWatershed,'watershed')

